#!/usr/bin/perl
# Jonathan Harlap 2006
# jharlap@bic.mni.mcgill.ca
# Perl tool to display a series in a dicomTar archive.
# $Id: displaySeries.pl,v 1.4 2007/04/23 13:56:01 jharlap Exp $

use strict;

use Cwd qw/ abs_path /;
use File::Find;
use File::Temp qw/ tempdir /;
use File::Basename qw/ basename dirname /;
use FindBin;

use lib "/usr/local/dicomSummary";
use DICOM::DICOM;

my $verbose = 0;

my $Usage = "------------------------------------------

$0 displays a DICOM series in a dicomTar archive.

Usage:\n\t $0 </PATH/TO/ARCHIVE> <series number>\n";

unless(scalar(@ARGV) == 2) {
	 print $Usage;
	 exit(1);
}


my $tarchive = $ARGV[0];
unless($tarchive =~ /^\//) {
	$tarchive = abs_path(dirname($tarchive)) . '/' . basename($tarchive);
}
my $targetSeriesNumber = $ARGV[1];

# create the temp dir
my $tempdir = tempdir( TMPDIR => 1, CLEANUP => 1 );

# extract the tarchive
my $dcmdir = &extract_tarchive($tarchive, $tempdir);

# get a list of files to display
my @filesToShow = ();

my $find_handler = sub {
	 my $file = $File::Find::name;
	 if(-f $file) {

		  # read the file, assuming it is dicom
		  my $dicom = DICOM->new();
		  $dicom->fill($file);
		  my $fileIsDicom = 1;
		  my $studyUID = $dicom->value('0020','000D');
		  
		  # see if the file was really dicom
		  if($studyUID eq "") {
				$fileIsDicom = 0;
		  }
		  
		  if($fileIsDicom) {
			  my $series = trimwhitespace($dicom->value('0020','0011')) + 0;
			  if($series == $targetSeriesNumber) {
				  push @filesToShow, $file;
			  }
		  }
	  }
 };
find($find_handler, "$tempdir/$dcmdir");

if(scalar(@filesToShow) == 0) {
	 print "Error: No files to be displayed.  Aborting.\n";
	 exit(1);
}

# move the series into a new dir
mkdir("$tempdir/seriesdir", 0755);
foreach my $file (@filesToShow) {
	`mv $file $tempdir/seriesdir`;
}

# show the series
my $DISPLAY_IN_MEDX = $FindBin::Bin . "/displaySeriesInMedx.pl";
my $cmd = "$DISPLAY_IN_MEDX $tempdir/seriesdir";
`$cmd`;
exit 0;



sub extract_tarchive {
	 my ($tarchive, $tempdir) = @_;

	 print "Extracting tarchive\n" if $verbose;
	 `cd $tempdir ; tar -xf $tarchive`;
	 opendir TMPDIR, $tempdir;
	 my @tars = grep { /\.tar\.gz$/ && -f "$tempdir/$_" } readdir(TMPDIR);
	 closedir TMPDIR;

	 if(scalar(@tars) != 1) {
		  print "Error: Could not find inner tar in $tarchive!\n";

		  print @tars . "\n";
		  exit(1);
	 }

	 my $dcmtar = $tars[0];
	 my $dcmdir = $dcmtar;
	 $dcmdir =~ s/\.tar\.gz$//;

	 `cd $tempdir ; tar -xzf $dcmtar`;
	 
	 return $dcmdir;
}



sub trimwhitespace {
	my $string = shift;
	$string =~ s/^\s+//;
	$string =~ s/\s+$//;
	return $string;
}
